package com.jmu.edu.IMApplication.adapter;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.net.bean.FriendInvite;
import com.jmu.edu.IMApplication.utils.FriendUtils;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class FriendNotificationItemAdapter extends RecyclerView.Adapter<FriendNotificationItemAdapter.MyViewHolder> {

    private static final String TAG = "好友通知适配器";
    private List<UserInfo> userInfoList = new ArrayList<>();
    private List<FriendInvite> friendInviteList;

    public void setFriendInviteList(List<FriendInvite> friendInviteList) {
        this.friendInviteList = friendInviteList;
        Log.d(TAG, "setFriendInviteList: size" + friendInviteList.size());
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_friend_notification, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        FriendInvite friendInvite = friendInviteList.get(position);
        //这个情况说明存在该userInfo
        if (position < userInfoList.size()) {
            UserInfo userInfo = userInfoList.get(position);
            fillViewWithValues(userInfo, friendInvite, holder, position);
        } else {
            Log.d(TAG, "onBindViewHolder: fromUsername:"+friendInvite.getFromUsername());
            //没有的话就先获得这个userInfo
            WillowUtils.getUserInfo(friendInvite.getFromUsername(), new GetUserInfoCallback() {
                @Override
                public void gotResult(int i, String s, UserInfo userInfo) {
                    if(i == 0){
                        Log.d(TAG, "gotResult: success");
                    }else{
                        Log.d(TAG, "gotResult: fail");
                    }
                    userInfoList.add(userInfo);
                    notifyItemChanged(position);
                    //fillViewWithValues(userInfo, friendInvite, holder, position);
                }
            });
        }


    }

    @Override
    public int getItemCount() {
        return friendInviteList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private ShapeableImageView avatarImage;
        private TextView nameText, signText, stateText;
        private MaterialButton agreeButton;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            avatarImage = itemView.findViewById(R.id.item_friend_notification_avatar);
            nameText = itemView.findViewById(R.id.item_friend_notification_nickname);
            signText = itemView.findViewById(R.id.item_friend_notification_sign);
            stateText = itemView.findViewById(R.id.item_friend_notification_state);
            agreeButton = itemView.findViewById(R.id.item_friend_notification_agree);
        }
    }

    public void fillViewWithValues(UserInfo userInfo, FriendInvite friendInvite, MyViewHolder holder, int position) {
        // state表示这个用户和我的状态，具体参数见属性
        int state = friendInvite.getStatus();
        holder.nameText.setText(WillowUtils.getNickName(userInfo));
        // 设置个性签名-- 后续改成添加好友的原因
        holder.signText.setText(WillowUtils.getSignature(userInfo));
        // 加载头像
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(holder.avatarImage).load(bitmap).into(holder.avatarImage);
                } else {
                    Glide.with(holder.avatarImage).load(R.drawable.smc).into(holder.avatarImage);
                }
            }
        });
        //根据state进行对应的界面调整
        switch (state) {
            case FriendUtils.RECEIVE:
                holder.agreeButton.setVisibility(View.VISIBLE);
                holder.stateText.setText("");
                holder.agreeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        acceptInvitation(friendInvite, holder, position);

                    }
                });

                break;
            case FriendUtils.AGREE:
                holder.stateText.setText("已同意");
                break;
            case FriendUtils.DISAGREE:
                holder.stateText.setText("已拒绝");
                break;
            case FriendUtils.WAIT:
                holder.stateText.setText("等待回应");
                break;
            default:
                break;
        }
    }

    private void acceptInvitation(FriendInvite friendInvite, MyViewHolder holder, int position) {
        //替换状态
        friendInvite.setStatus(FriendUtils.AGREE);
        //发送更换数据到服务器
        String url = HttpUtil.URL_UPDATE_USER_INVITE + "?fromUsername=" + friendInvite.getFromUsername()
                + "&toUsername=" + friendInvite.getToUsername()
                + "&status=" + friendInvite.getStatus();
        Request request = new Request.Builder().url(url).get().build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: 接受好友请求", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: 接受好友请求");
            }
        });
        //和IM框架进行交互
        FriendUtils.acceptInvitation(friendInvite.getFromUsername(), new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    //隐藏同意按钮
                    holder.agreeButton.setVisibility(View.GONE);
                    holder.stateText.setText("已同意");
                    Log.d("好友通知适配器", "同意添加好友");
                }
            }
        });
    }
}
